package wikichat.android.intelimed;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SQLiteHelper extends SQLiteOpenHelper {
	
	private static String DATABASE_NAME = "my_database.db";
	private static String DATABASE_PATH = "/data/data/wikichat.android.intelimed/databases/";
	private static final int DATABASE_VERSION = 1;
	
	private final Context context;
	public SQLiteDatabase dataBase;

	public SQLiteHelper(Context context) {
		super(context, DATABASE_NAME, null, 1);
		this.context = context;
	}

	private boolean checkDataBase() {
		File dbFile = new File(DATABASE_PATH + DATABASE_NAME);
		return dbFile.exists();
	}
	
	public void createDataBase() {
		boolean dbExist = checkDataBase();
		
		if(dbExist == false){
			this.getReadableDatabase();
			try{
				copyDataBase();
			}catch(IOException e){
				throw new Error("Error copying database");
			}
		}
	}
	
	private void copyDataBase() throws IOException {
		InputStream myInput = context.getAssets().open(DATABASE_NAME);
		String outFileName = DATABASE_PATH + DATABASE_NAME;
		OutputStream myOutput = new FileOutputStream(outFileName);
		byte[] buffer = new byte[1024];
		int length;
		while((length = myInput.read(buffer))>0){
			myOutput.write(buffer, 0, length);
		}
		myOutput.flush();
		myOutput.close();
		myInput.close();
	}
	
	public void openDataBase() throws SQLException {
		String myPath = DATABASE_PATH + DATABASE_NAME;
		dataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
	}
	
	public synchronized void close(){
		if(dataBase != null){
			dataBase.close();
		}
		super.close();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		
	}

}
